package com.sentinel.demo02.datasource;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.util.List;

@Slf4j
public class MyFileDatasource implements InitFunc {
    /**
     * 初始化方法，按需实现代码
     */
    @Override
    public void init() throws Exception {
        // 1.找到配置文件
        URL resource = this.getClass().getClassLoader().getResource("sentinel.json");
        log.info("文件资源:{}",resource);
        String path = resource.getPath();
        log.info("文件路径:{}",path);
        // 2.利用sentinel的api读取配置文件，生成一个规则的json对象(fileDatasource)
        FileRefreshableDataSource<List<FlowRule>> fileDatasource =
                new FileRefreshableDataSource<>(path, json -> {
                    log.info("文件内容:{}",json);
                    //使用fastjson将json字符串转换成对象
                    return JSON.parseArray(json,FlowRule.class);
                });
        // 3.将规则json对象加载到sentinel
        FlowRuleManager.register2Property(fileDatasource.getProperty());
        log.info("自定义数据初始化完成");
    }
}
